package com.camel.base.template;

import com.baomidou.mybatisplus.core.injector.AbstractMethod;
import com.baomidou.mybatisplus.core.metadata.TableInfo;
import com.camel.core.annotations.AssociationField;
import org.apache.ibatis.mapping.MappedStatement;
import org.apache.ibatis.mapping.SqlSource;
import org.springframework.util.ObjectUtils;

import java.lang.reflect.Field;

/**
 * @author 86183
 */
public class SelectIndex extends AbstractMethod {
    @Override
    public MappedStatement injectMappedStatement(Class<?> mapperClass, Class<?> modelClass, TableInfo tableInfo) {
        Field[] declaredFields = tableInfo.getEntityType().getDeclaredFields();
        StringBuilder stringBuilder = new StringBuilder(this.sqlSelectColumns(tableInfo, true));

        for (Field field : declaredFields) {
            AssociationField associationField = field.getAnnotation(AssociationField.class);
            if (!ObjectUtils.isEmpty(associationField)) {
                stringBuilder.append(", (" + associationField.select() + ") AS " + associationField.name());
            }
        }

        /* 执行 SQL ，动态 SQL 参考类 SqlMethod */
        String sql = String.format("<script>%s SELECT %s FROM %s %s %s\n</script>",
                this.sqlFirst(),
                stringBuilder.toString(),
                tableInfo.getTableName(),
                this.sqlWhereEntityWrapper(true, tableInfo),
                this.sqlComment());

        /* mapper 接口方法名一致 */
        String method = "selectIndex";
        SqlSource sqlSource = languageDriver.createSqlSource(configuration, sql, modelClass);
        // 查询方法对应addSelectMappedStatementForTable
        return addSelectMappedStatementForTable(mapperClass, method, sqlSource, tableInfo);
    }
}
